package com.itic.mall.system.orderexpress.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.imports.ImportExcelUtil;
import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.applications.sys.syssetting.service.SysSettingService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.persistence.model.OrderExample;
import com.itic.mall.system.order.service.OrderService;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpress;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpressExample;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpressExample.Criteria;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpressVo;
import com.itic.mall.system.orderexpress.service.OrderExpressService;


@Controller
@RequestMapping(value="/system/orderexpress")
public class OrderExpressController
     extends BaseController {
	public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
	//配置您申请的KEY
    public static final String APPKEY ="*************************";
   
    @Autowired
    private OrderExpressService orderExpressService;

    @Autowired
   	protected OutCommonService outCommonService;
    
    @Autowired
   	protected OrderService orderService;
    
    @Autowired
    protected SysSettingService sysSettingService;
       
       //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
       private static final String MODEL_NAME_CHINA = "物流管理";//中文名
       private static final String MODEL_NAME＿ENGLISH = "orderexpress";//英文名
       private static final String PAGE_COMMON_PATH = "/mall/system/orderexpress/orderexpress";//通用路径
       private static final String COMMON_URL = "/system/orderexpress/";//通用路径

       private static final String WULIU = "T_MALL_ORDER_WULIU";//物流代码详情
       //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
      
       /*
        * 主页面
        */
       @RequestMapping(value="/init")
       public String init(Model model){
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"Main";
       }
       
       /*
        * 添加页面
        */
       @RequestMapping(value="/initAdd")
       public String initAdd(Model model){
       	model.addAttribute("name_china", MODEL_NAME_CHINA);
       	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
       	model.addAttribute("common_url", COMMON_URL);
       	return PAGE_COMMON_PATH+"Add";
       }
       
       /*
        * 编辑页面
        */
       @RequestMapping(value="/initEdit")
       public String initEdit(String id , Model model){
       	if( StringHelper.isNotBlank(id) ) {
       		OrderExpress temp = orderExpressService.get(id);
       		model.addAttribute("editData",iticJsonMapper.toJson(temp));
       		model.addAttribute("name_china", MODEL_NAME_CHINA);
           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
           	model.addAttribute("common_url", COMMON_URL);
       	}else {
               throw new ParameterErrorException();
           }
       	return PAGE_COMMON_PATH+"Edit";
       }
       
       /*
        * 查看页面
        */
       @RequestMapping(value="/initView")
       public String initView(String id , Model model){
       	if( StringHelper.isNotBlank(id) ) {
       		
       		OrderExpress temp  = orderExpressService.get(id);
       		
       		
       		
       		
       		String key = APPKEY;
       		String byKey = sysSettingService.getByKey("MALL_WULIU_KEY");
			if( StringHelper.isNotBlank(byKey) ){
					key = byKey;
			}
			Object data = getRequest1( key, temp.getExpressName(),  temp.getExpressNum() );
			model.addAttribute("viewEditWulius",iticJsonMapper.toJson(data));
			
			temp.setExpressName(outCommonService.getNameByCode(WULIU, temp.getExpressName()));
			model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
			
       		model.addAttribute("name_china", MODEL_NAME_CHINA);
           	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
           	model.addAttribute("common_url", COMMON_URL);
       	}else {
               throw new ParameterErrorException();
           }
       	
       	return PAGE_COMMON_PATH+"View";
       }
       
       @RequestMapping(value="/initImp")
       public String initImp( Model model ){
			
      		model.addAttribute("name_china", MODEL_NAME_CHINA);
          	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
          	model.addAttribute("common_url", COMMON_URL);
          	return PAGE_COMMON_PATH+"Imp";
       }
       
       //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
       
       /**
        * 添加模板管理数据
        * @param android
        * @return
        */
       @RequestMapping(value="/add")
       @ResponseBody
       public Map<String,String> add(OrderExpress temp){
       	
       	 Map<String, String> resultMap = new HashMap<String, String>();
            String result = ResponseCode.SERVER_ERROR.getCode();
            result = orderExpressService.add(temp);
            
            resultMap.put(IticConst.RESULT, result);
            return resultMap;
       }
       
       
       /**
        * <p>Title:queryCondition </p>
        * <p>Description:封装查询条件 </p>
        * @param jzdw
        * @param jzdwExample
        * @return
        */
       private OrderExpressExample queryCondition(HttpServletRequest request,OrderExpress temp,String orderNum) {
       	
       	// 参数处理
           OrderExpressExample example = new OrderExpressExample();
           // 按创建时间倒序
           example.setOrderByClause("CREATE_TIME DESC");
           // 按排列号顺序
           example.setOrderByClause("REORDER ASC");
           
           Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
           
           // 查询条件
           if ( null != temp ) {
       	  
        	   if( StringHelper.isNotBlank(temp.getExpressName()) ){
        		   criteria.andExpressNameEqualTo(temp.getExpressName());   
        	   }
        	   
        	   if( StringHelper.isNotBlank(temp.getExpressNum()) ){
        		   criteria.andExpressNumLike("%"+ temp.getExpressNum() + "%");
        	   }
        	   
        	   if( StringHelper.isNotBlank(orderNum) ){
        		    // 获取订单号码的id
        		    List<String> ids = orderService.getIdsLikeOrderNum("%"+orderNum+"%");
        		    if( ids.size()>0 ){
        		    	criteria.andOrderIdIn(ids);
        		    }else{
        		    	criteria.andIdEqualTo("null");
        		    }
        	   }
        	   
           }
           return example;
       }
       
       /**
        * 
        * @param goldType
        * @param request
        * @return
        */
       @RequestMapping(value = "/list")
       @ResponseBody
       public Map<String, Object> list(OrderExpress temp, HttpServletRequest request,String orderNum){
           // 声明返回对象
           Map<String, Object> resultMap = new HashMap<String, Object>();
           
           
           OrderExpressExample example = this.queryCondition(request,temp,orderNum);
           // 封装分页参数
           example = this.handlePageQuery(request, example);
           
           
           // 获取信息总条数
           int total = orderExpressService.count(example);
           
           // 获取数据
           List<OrderExpress> list = orderExpressService.list(example);
           if( list.size() > 0 ){
        	   for( OrderExpress tmp: list ){
        		   tmp.setExpressName( outCommonService.getNameByCode(WULIU, tmp.getExpressName()) );
        	   }
           }
           
           // 数据返回处理
           resultMap.put(IticConst.TOTAL_RECORDS, total);
           resultMap.put(IticConst.DISPLAY_RECORDS, total);
           resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
           resultMap.put(IticConst.DATA, list);
           return resultMap;

       }
       
       /**
        * 编辑保存
        * @param Order
        * @return
        */
       @RequestMapping(value="/edit")
       @ResponseBody
       public Map<String,String> edit( String delFileIds , OrderExpress temp ){
       
       	    Map<String, String> resultMap = new HashMap<String, String>();
            String result = ResponseCode.SERVER_ERROR.getCode();
            result = orderExpressService.edit(temp);
            
            resultMap.put(IticConst.RESULT, result);
            return resultMap;
       }

       /**
        * 删除
        * 
        */
       @RequestMapping(value = "/del")
       @ResponseBody
       public Map<String, String> del(String id) {
           Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();


           if( StringHelper.isNotBlank(id) ){
        	   OrderExpress temp = new OrderExpress();
               temp.setId(id);
               result = orderExpressService.delete(temp);
           }
           
           resultMap.put(IticConst.RESULT, result);
           return resultMap;
       }
       
       
       //1.常用快递查询API
       public static Object getRequest1( String key, String wuliuType, String wuliuNum ){
       	Object result = null;
           String url ="http://v.juhe.cn/exp/index";//请求接口地址
           Map<String,Object> params = new HashMap<String,Object>();//请求参数
               params.put("com",wuliuType);//需要查询的快递公司编号
               params.put("no",wuliuNum);//需要查询的订单号
               params.put("key",key);//应用APPKEY(应用详细页查询)
               params.put("dtype","json");//返回数据的格式,xml或json，默认json
    
           try {
               result =net(url, params, "GET");
               JSONObject object = JSONObject.fromObject(result);
               if(object.getInt("error_code")==0){
               	JSONObject object2 = object.getJSONObject("result");
               	Object object3 = object2.get("list");
                   result = object3;
               }else{
                   result = object.get("error_code")+":"+object.get("reason");
               }
           } catch (Exception e) {
               e.printStackTrace();
           }
           return result;
       }
    
    
       /**
        *
        * @param strUrl 请求地址
        * @param params 请求参数
        * @param method 请求方法
        * @return  网络请求字符串
        * @throws Exception
        */
       public static String net(String strUrl, Map params,String method) throws Exception {
           HttpURLConnection conn = null;
           BufferedReader reader = null;
           String rs = null;
           try {
               StringBuffer sb = new StringBuffer();
               if(method==null || method.equals("GET")){
                   strUrl = strUrl+"?"+urlencode(params);
               }
               URL url = new URL(strUrl);
               conn = (HttpURLConnection) url.openConnection();
               if(method==null || method.equals("GET")){
                   conn.setRequestMethod("GET");
               }else{
                   conn.setRequestMethod("POST");
                   conn.setDoOutput(true);
               }
               conn.setRequestProperty("User-agent", userAgent);
               conn.setUseCaches(false);
               conn.setConnectTimeout(DEF_CONN_TIMEOUT);
               conn.setReadTimeout(DEF_READ_TIMEOUT);
               conn.setInstanceFollowRedirects(false);
               conn.connect();
               if (params!= null && method.equals("POST")) {
                   try {
                       DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                           out.writeBytes(urlencode(params));
                   } catch (Exception e) {
                       // TODO: handle exception
                   }
               }
               InputStream is = conn.getInputStream();
               reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
               String strRead = null;
               while ((strRead = reader.readLine()) != null) {
                   sb.append(strRead);
               }
               rs = sb.toString();
           } catch (IOException e) {
               e.printStackTrace();
           } finally {
               if (reader != null) {
                   reader.close();
               }
               if (conn != null) {
                   conn.disconnect();
               }
           }
           return rs;
       }
    
       //将map型转为请求参数型
       public static String urlencode(Map<String,Object>data) {
           StringBuilder sb = new StringBuilder();
           for (Map.Entry i : data.entrySet()) {
               try {
                   sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
               } catch (UnsupportedEncodingException e) {
                   e.printStackTrace();
               }
           }
           return sb.toString();
       }
       
       /**
        * exp
        * 
        */
       @SuppressWarnings("unchecked")
   	@RequestMapping(value = "/imp")
       @ResponseBody
       public Map<String, String> imp(HttpServletRequest request,String fileId) {
       	Map<String, String> resultMap = new HashMap<String, String>();
           String result = ResponseCode.SERVER_ERROR.getCode();
       	 try {
                // 获取Excel解析数据
                Map<String, Object> excelDataMap = new HashMap<String, Object>();
                String filePath = outCommonService.getFilePath(fileId);
                if (StringHelper.isNotBlank(filePath)) {
               	   excelDataMap = ImportExcelUtil.readValue( new File(FileHelper.getRootDir(), filePath), MODEL_NAME＿ENGLISH );
                }
                // 获取验证错误List集合
                List<String> errorInfoList =  (List<String>) excelDataMap.get("error");
                // 获取对象组成的List集合
                List<OrderExpressVo> dataList = (List<OrderExpressVo>) excelDataMap .get("data");                 
                if (errorInfoList != null && errorInfoList.size() > 0) {
                    // 处理错误信息，返回前台
                    result = "error";
                    resultMap.put(IticConst.DATA, "ERROR");
                    request.getSession().setAttribute("ExcelImpError",
                            errorInfoList);
                } else if (dataList != null && dataList.size() > 0) {
                    //处理excel数据
               	    result = orderExpressService.imp(request,dataList);
                }
            
            } catch (Exception e) {
           	 throw new RuntimeException("[OrderExpressController | imp 模板示例导入异常]");
            } 
       	 resultMap.put(IticConst.RESULT, result);
            return resultMap; 
       } 
       
}